package sunyu.tools.http;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component("httpConnectionManager")
public class HttpConnectionManager {

    PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = null;

    @Value("${http.maxTotal}")
    private int maxTotal;
    @Value("${http.defaultMaxPerRoute}")
    private int defaultMaxPerRoute;

    @PostConstruct
    public void init() {
        poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
        poolingHttpClientConnectionManager.setMaxTotal(maxTotal);
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
    }

    @PreDestroy
    public void destroy() {
        poolingHttpClientConnectionManager.close();
    }

    public CloseableHttpClient getHttpClient() {
        // CloseableHttpClient httpClient = HttpClients.createDefault();//如果不采用连接池就是这种方式获取连接
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager).build();
        return httpClient;
    }

}
